package com.itheima.utils;

import org.dom4j.xpp.ProxyXmlStartTag;

import java.lang.reflect.Proxy;
import java.util.List;

public class DefaultSession implements Session{

    private Configuration configuration;
    private Executor executor;

    public  DefaultSession(Configuration configuration) {

        this.configuration = configuration;
        executor = new Executor(configuration);
    }

    public <E> List<E> select(String statment) throws Exception {

        Mapper mapper = configuration.getMappers().get(statment);
        List<E> list = executor.selectList(mapper.getSql(), mapper.getResultType());
        return list;
    }

    public <E> E selectOne(String statment, Object ... parameters) throws Exception {

        System.out.println("selectOne--->"+parameters);
        Mapper mapper = configuration.getMappers().get(statment);
        E o = executor.selectOne(mapper.getSql(), mapper.getResultType(), parameters);
        return o;
    }

    public void insert(String statment, Object pojo) throws Exception {

        Mapper mapper = configuration.getMappers().get(statment);
        executor.insert(mapper.getSql(), pojo);
    }

    public void update(String statment, Object pojo) throws Exception {

        Mapper mapper = configuration.getMappers().get(statment);
        executor.update(mapper.getSql(), pojo);
    }

    public <T> T getMapper(Class<T> clazz) {

        return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new MapperProxyFactory(this));
        //return (T) Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), new MapperProxyFactory(this));
    }

    public void close() {

    }

    public void commit() {

    }
}
